<template>
  <div class="app-container">
        <el-form :inline="true" ref="queryForm" :model="queryParams" v-show="showSearch" @keyup.enter.native="queryDataList()">
            <el-form-item label="合同名称">
                <el-input  size="small" v-model="queryParams.contractName" placeholder="请输入合同名称" clearable/>
            </el-form-item>
            <el-form-item label="合同状态">
                <el-select  size="small"  v-model="queryParams.status" value="queryItems[1].value"
                           placeholder="请选择合同状态"
                           clearable
                           style="margin-left: 5px;">
                    <el-option
                            v-for="item in statusOptions"
                            :key="item.value"
                            :label="item.name"
                            :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="合同所属公司" v-if="$store.state.name === 'admin'">
                <el-select
                        size="small"
                        v-model="queryParams.clientId"
                        filterable
                        remote
                        clearable
                        reserve-keyword
                        placeholder="请输入企业名称关键词"
                        :remote-method="remoteMethod"
                        :loading="loading"
                        style="width: 320px">
                    <el-option
                            v-for="item in companyList"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="创建时间">
                <el-date-picker v-model="dateRange" size="small" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
            <!--      <el-form-item>-->
            <!--        <el-button v-if="$hasPermission('sys:contract:save')" type="primary" @click="addOrUpdateHandle()">{{ $t('add') }}</el-button>-->
            <!--      </el-form-item>-->
            <!--              <el-form-item>-->
            <!--                <el-button v-if="$hasPermission('sys:contract:delete')" type="danger" @click="deleteHandle()">{{ $t('deleteBatch') }}</el-button>-->
            <!--              </el-form-item>-->
        </el-form>
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                        v-hasPermi="['sys:contract:create']"
                        type="primary"
                        icon="el-icon-plus"
                        size="mini"
                        @click="handleAdd"

                >创建合同</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
        <el-table
                size="mini"
                v-loading="loading"
                :data="contractList"
                border
                stripe
                style="width: 100%;">
            <!--            <el-table-column type="selection" header-align="center" align="center" width="50"/>-->
            <el-table-column prop="contractNo" :label="$t('contract.contractNo')" header-align="center" align="center" width="220">
                <template slot-scope="scope">
                    <el-button type="text" @click="contractDetailList(scope.row)">{{ scope.row.contractNo }}</el-button>
                </template>
            </el-table-column>
            <el-table-column prop="contractName" :label="$t('contract.contractName')" header-align="center" align="center">
            </el-table-column>
            <el-table-column prop="clientName" :label="$t('contract.clientName')" header-align="center" align="center" show-overflow-tooltip/>
            <el-table-column prop="customerName" :label="$t('contract.customerName')" header-align="center" align="center" width="100"/>
            <el-table-column prop="amount" :label="$t('contract.amount')" header-align="center" align="center" width="140"/>
            <el-table-column prop="contractAmount" :label="$t('contract.contractAmount')" header-align="center" align="center" width="140"/>
            <el-table-column prop="status" :label="$t('contract.status')" header-align="center" align="center" width="100">
                <template slot-scope="scope">
                    <el-tag v-if="scope.row.status === '0'" size="mini" type="info">{{ $t('contract.status0') }}</el-tag>
                    <el-tag v-else-if="scope.row.status === '1'" size="mini" type="warning">{{ $t('contract.status1') }}
                    </el-tag>
                    <el-tag v-else-if="scope.row.status === '2'" size="mini">{{ $t('contract.status2') }}</el-tag>
                    <el-tag v-else-if="scope.row.status === '3'" size="mini" type="warning">{{ $t('contract.status3') }}
                    </el-tag>
                    <el-tag v-else-if="scope.row.status === '4'" size="mini" type="success">{{ $t('contract.status4') }}
                    </el-tag>
                    <el-tag v-else-if="scope.row.status === '5'" size="mini" type="danger">{{ $t('contract.status5') }}
                    </el-tag>
                    <el-tag v-else-if="scope.row.status === '6'" size="mini" type="danger">{{ $t('contract.status6') }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="isPay" label="支付状态" header-align="center" align="center" width="120">
                <template slot-scope="scope">
                    <el-tag v-if="scope.row.isPay === 0" size="mini" type="danger">未支付</el-tag>
                    <el-tag v-else-if="scope.row.isPay === 1" size="mini" type="success">已支付</el-tag>
                    <el-tag v-else-if="scope.row.isPay === 2" size="mini" type="warning">退款中</el-tag>
                    <el-tag v-else-if="scope.row.isPay === 3" size="mini" type="info">已退款</el-tag>
                    <el-tag v-else-if="scope.row.isPay === 4" size="mini" type="info">拒绝退款</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="datumStatus" :label="$t('contract.datumStatus')" header-align="center" align="center" width="120">
                <template slot-scope="scope">
                    <el-tag v-if="scope.row.datumStatus === 0" size="mini" type="danger">{{ $t('contract.datumStatus0')}}</el-tag>
                    <el-tag v-else-if="scope.row.datumStatus === 1" size="mini" type="success">{{$t('contract.datumStatus1') }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="creator" :label="$t('createBy')" header-align="center" align="center" width="80"/>
            <el-table-column prop="createTime" :label="$t('createTime')" header-align="center" align="center" width="140"/>
            <el-table-column :label="$t('handle')" fixed="right" header-align="center" align="center" width="180">
                <template slot-scope="scope">
                    <el-button v-hasPermi="['sys:contract:input']" v-if="scope.row.status === '0'" type="text" size="mini" @click="handlerAddContractShow(scope.row)">录入合同</el-button>
                    <el-button v-hasPermi="['sys:contract:lock']" v-if="parseInt(scope.row.status) < 1" type="text" size="mini" @click="handlerLockContract(scope.row)">锁定合同</el-button>
                    <el-button v-hasPermi="['sys:contract:payment']" v-if="scope.row.status === '0' && scope.row.customerId === 0" type="text" size="mini" @click="handlerContractCustomerDialogShow(scope.row)">付费客户</el-button>
                    <el-button v-hasPermi="['sys:contract:uploadDatum']" v-if="scope.row.status === '4' && scope.row.datumStatus !== 1" type="text" size="mini" @click="addOrUpdateHandle(scope.row)">{{ $t('uploadDatum') }}</el-button>
                    <el-button v-hasPermi="['sys:contract:look']"  type="text" size="mini" @click="contractDetailList(scope.row)">{{ $t('look') }}</el-button>
                    <el-button v-hasPermi="['sys:contract:look']" v-if="scope.row.status === '4'" type="text" size="mini" @click="downloadContract(scope.row.id)">{{ $t('download') }}</el-button>
                    <el-button v-hasPermi="['sys:contract:delete']" v-if="(scope.row.status === '0' || scope.row.status === '1')" type="text" size="mini" @click="handleDelete(scope.row)">{{ $t('delete') }}
                    </el-button>
                    <el-button v-hasPermi="['sys:contract:refund']" v-if="((scope.row.isPay === 1 || scope.row.isPay === 4) && (scope.row.status === '3' || scope.row.status === '4'))" type="text" size="mini" @click="openRefundDialog(scope.row.id)">退款
                    </el-button>
                    <el-button v-hasPermi="['sys:contract:cancel']" v-if="(scope.row.status === '2' || scope.row.status === '3' || scope.row.status === '4' || scope.row.status === '6')" type="text" size="mini" @click="cancelContract(scope.row)">作废
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <pagination
                v-show="total>0"
                :total="total"
                :page.sync="queryParams.current"
                :limit.sync="queryParams.size"
                @pagination="getList"
        />

        <!-- 弹窗, 新增 / 修改 -->
        <!--合同资料上传-->
        <add-or-update v-if="addOrUpdateVisible" :contract-id="contractId" ref="addOrUpdate" @refreshDataList="getList"/>

        <contract-flow-list  ref="detailOrUpdate" v-if="detailDialogVisible" :parent-id="parentId" :status="statusCode"/>


        <el-dialog :visible="refundDialogVisible" title="退款申请" width="35%" :show-close="false">
            <el-form :model="refundForm" label-width="100px">
                <el-form-item label="退款原因" prop="applyDesc">
                    <el-input type="textarea" v-model="refundForm.applyDesc" placeholder="请输入退款原因" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="refund" size="mini">确定</el-button>
                <el-button @click="refundDialogVisible = false" size="mini">取消</el-button>
            </div>
        </el-dialog>

        <!--合同名称创建-->
        <el-dialog :visible="contractNameAddDialogVisible" title="合同创建" width="35%" append-to-body :show-close="false">
            <el-form :model="contractForm" label-width="100px" >
                <el-form-item label="合同名称" prop="contractName">
                    <el-input size="small" v-model="contractForm.contractName" placeholder="请输入合同名称" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" size="mini" @click="handleCreateContractName">确定</el-button>
                <el-button @click="handlerCancel" size="mini" >取消</el-button>
            </div>
        </el-dialog>

        <el-dialog :visible="contractCustomerDialogVisible" title="合同付费客户" width="35%" append-to-body :show-close="false">
            <el-form  label-width="80px" inline>
                <el-form-item label="手机号码" prop="applyDesc">
                    <el-input size="small" v-model="paymentCustomerPhone" placeholder="请输入手机号码" />
                </el-form-item>
                <el-form-item>
                    <el-button type="cyan" icon="el-icon-search" size="mini" @click="getCustomerByPhone">搜索</el-button>
                </el-form-item>
            </el-form>
            <el-card class="box-card" v-if="this.contractPaymentCustomer !== undefined">
                <div slot="header" class="clearfix">
                    <span style="font-size: medium; font-weight: 600; "><i class="el-icon-user" style="margin-right: 10px; color: #2f74ff;  font-size: 24px;"/>{{contractPaymentCustomer.name}}</span>
                </div>
                <div style="font-size: medium; font-weight: 600; "><i class="el-icon-mobile-phone" style="margin-right: 10px; color: #2f74ff; font-size: 24px;"/>{{contractPaymentCustomer.mobile}}</div>
            </el-card>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" size="mini" :disabled="this.contractPaymentCustomer === undefined" @click="handlerContractCustomerAdd()">确定</el-button>
                <el-button size="mini" @click="handlerCancel">取消</el-button>
            </div>
        </el-dialog>

        <el-dialog :visible="contractAddDialogVisible" title="合同录入" width="60%" append-to-body :show-close="false">
            <el-form :model="contractForm" label-width="120px" >
                <el-form-item label="合同模版:" prop="contractTemplate" style="font-weight: bolder; font-size: medium; ">
                    <el-select
                            v-model="contractForm.templateId"
                            @change="handleTemplateSelected"
                            placeholder="请选择合同模版"
                            :loading="loading"  style="width: 480px">
                        <el-option
                                v-for="item in contractTemplates"
                                :key="item.id"
                                :label="item.templeteName"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-row>
                <template v-for="formItem in contractForm.formItems">
                    <el-col :span="24" style="margin-bottom: 15px;">
                        <label style="font-size: medium; font-weight: bolder; margin-left: 50px;">{{formItem.label}}:</label>
                        <div class="top-right-btn" v-if="formItem.type>0">
                            <el-row>
                                <el-tooltip class="item" effect="dark" content="选择签署客户" placement="top">
                                    <el-button size="mini" :type="formItem.tips===''?'primary':'success'" :icon="formItem.tips===''?'el-icon-plus':'el-icon-check'" @click="customerChoose(formItem)">{{formItem.tips===''?'选择签署客户':formItem.tips}}</el-button>
                                </el-tooltip>
                            </el-row>
                        </div>
                        <el-divider direction="horizontal" class="el-divider--horizontal"></el-divider>
                        <template v-for="item in formItem.items" >
                            <!--// 0文本，1身份证 2日期 3手机号 4数字 5签章 6借款期数 7月利率 8还款方式 9每月还款日 10合同金额)-->
                            <template v-if="item.require>=0">
                            <el-form-item :label="item.placeholderName" label-width="180px" v-if="item.placeholderTag === 0 || item.placeholderTag === 1 || item.placeholderTag === 3 || item.placeholderTag === 4 || item.placeholderTag === 6 || item.placeholderTag === 7 || item.placeholderTag === 9 || item.placeholderTag === 10 ">
                                <el-input v-model="contractFormItems[item.placeholderKey]" :placeholder="`请输入${item.placeholderName}`" />
                            </el-form-item>
                            <el-form-item :label="item.placeholderName" label-width="180px" v-else-if="item.placeholderTag === 2">
                                <el-date-picker v-model="contractFormItems[item.placeholderKey]" value-format="yyyy-MM-dd" type="date" :placeholder="`请选择${item.placeholderName}`" />
                            </el-form-item>
                            <el-form-item :label="item.placeholderName" label-width="180px" v-else-if="item.placeholderTag === 8">
                                <el-select v-model="contractFormItems[item.placeholderKey]" :placeholder="`请选择${item.placeholderName}`">
                                    <el-option
                                            v-for="item in repaymentTypes"
                                            :key="item"
                                            :label="item"
                                            :value="item">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </template>
                        </template>
                    </el-col>

                </template>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" size="mini" :disabled="contractSigners.length < 2" @click="handleContractAdd()">确定</el-button>
                <el-button size="mini" @click="handlerCancel">取 消</el-button>
            </div>
        </el-dialog>

        <el-dialog :visible="customerChooseDialogVisible" :title="customerChooseTile" width="35%" append-to-body :show-close="false">
            <el-form  label-width="80px" inline>
                <el-form-item label="手机号码" prop="applyDesc">
                    <el-input size="small" v-model="customerPhone" placeholder="请输入手机号码" />
                </el-form-item>
                <el-form-item>
                    <el-button type="cyan" icon="el-icon-search" size="mini" @click="customerSearch">搜索</el-button>
                    <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                </el-form-item>
            </el-form>
            <el-card class="box-card" v-if="this.customerInfo !== undefined">
                <div slot="header" class="clearfix">
                    <span style="font-size: medium; font-weight: 600; "><i class="el-icon-user" style="margin-right: 10px; color: #2f74ff;  font-size: 24px;"/>{{customerInfo.name}}</span>
                </div>
                <div style="font-size: medium; font-weight: 600; "><i class="el-icon-mobile-phone" style="margin-right: 10px; color: #2f74ff; font-size: 24px;"/>{{customerInfo.mobile||customerInfo.contactMobile}}</div>
            </el-card>

            <div slot="footer" class="dialog-footer">
                <el-button type="primary" :disabled="this.customerInfo === undefined" size="mini"  @click="addContractSigners">确定</el-button>
                <el-button size="mini" @click="customerSearchAddCancel">取 消</el-button>
            </div>
        </el-dialog>

  </div>


</template>

<script>
    import {mapMutations} from 'vuex'
    // import mixinViewModule from '@/mixins/view-module'
    import AddOrUpdate from './contract-datum-add-or-update'
    import ContractFlowList from './contract-flow-list'
    import { listContract, getContract, delContract, updateContract, refund, exportContract, cancelContract, getTemplateList, getTemplateFieldsById,getCustomerByPhone,createContract,addContractCustomer,saveContractDetail,lockAndProduceContract} from "@/api/zfw/contract/contract";

    import {moduleRoutes} from '@/router'
    /* 合同列表 */
    export default {
        name:'contract-contract',
        // mixins: [mixinViewModule],
        data() {
            return {
                mixinViewModuleOptions: {
                    getDataListURL: '/manager/contract/list',
                    getDataListIsPage: true,
                    deleteURL: '/manager/contract/delete',
                    deleteIsBatch: true
                },
              refundDialogVisible: false,
                detailDialogVisible: false,
                contractDatumUploadVisible: false,
                addOrUpdateVisible:false,
                contractAddDialogVisible:false,
                customerChooseDialogVisible:false,
                contractNameAddDialogVisible:false,
                contractCustomerDialogVisible:false,
                customerChooseTile:'',
                contractForm:{
                    formItems:[],
                    templateId:undefined,
                    templateRecordId:undefined,
                    contractName:undefined
                },
                contractFormItems:{},//合同表单formitems数据绑定
                // 日期范围
                dateRange: [],
                // 合同签署流程状态字典
                statusOptions: [],// （0草稿 1合同制作中 2待付费3签署中 4签署完成5作废6合同制作失败）
                // 资料上传状态: 0- 未完成 1-已完成字典
                datumStatusOptions: [],
                // 合同主表格数据
                contractList: [],
                customerType:0,//客户类型
                customerIndex:0,
                customerLabel:'',
                customerPhone:undefined,//客户手机号码
                customerInfo:undefined,
                paymentCustomerPhone:'',//付费客户手机号
                contractPaymentCustomer:undefined,//合同付费客户
                repaymentTypes: ['等额本息', '等额本金', '先息后本'],
                contractSigners:[], //合同签署人,多人
                currentContractSingerFormItem:undefined,//当前合同签署客户表单模块
                // 选中数组
                ids: [],
                // 非单个禁用
                single: true,
                // 非多个禁用
                multiple: true,
                // 显示搜索条件
                showSearch: true,
                // 总条数
                total: 0,
                loading: false,
                contractId: 0, // 当前合同流程id
                parentId: 0,
                statusCode: 0,
                dataForm: {},
                companyList: [],
                queryItems:{
                    status: undefined,
                    contractName:'',
                    clientId:undefined
                },
                // 查询参数
                queryParams: {
                    current: 1,
                    size: 10,
                    contractNo: null,
                    contractName: null,
                    status: null,
                    amount: null,
                    contractAmount: null,
                    clientId: null,
                    clientName: null,
                    customerName: null,
                    createTime: null,
                },
                order: 'DESC',
                orderField: 'createTime',
                contractTemplates:[],//合同模版
              refundForm: {
                contractId: null,
                applyDesc: ''
              }
            }
        },
        components: {
            AddOrUpdate,
            ContractFlowList
        },
        created() {
            this.getList();
            this.getDicts("sys_contract_flow_status").then(response => {
                this.statusOptions = response.data;
            });
            this.getDicts("sys_contract_datum_status").then(response => {
                this.datumStatusOptions = response.data;
            });
        },
        methods: {
            ...mapMutations('d2admin/page', {
                d2adminPagePoolPush: 'push'
            }),
            /** 查询合同主列表 */
            getList() {
                this.loading = true;
                listContract(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
                    this.contractList = response.data.records;
                    this.total = response.data.total;
                    this.loading = false;
                });
            },
            // 合同签署流程状态字典翻译
            statusFormat(row, column) {
                return this.selectDictLabel(this.statusOptions, row.status);
            },
            // 资料上传状态: 0- 未完成 1-已完成字典翻译
            datumStatusFormat(row, column) {
                return this.selectDictLabel(this.datumStatusOptions, row.datumStatus);
            },
            /** 重置按钮操作 */
            resetQuery() {
                this.dateRange = [];
                this.resetForm("queryForm");
                this.handleQuery();
            },
            /** 搜索按钮操作 */
            handleQuery() {
                this.queryParams.current = 1;
                this.getList();
            },

            /** 创建合同名称 */
            handleCreateContractName(){
                if(this.contractForm.contractName === '' || this.contractForm.contractName.length <= 3){
                    this.$message.error("合同名称不少于3个字");
                    return;
                }
                let params = {
                    contractName: this.contractForm.contractName
                };
                createContract(params).then(result =>{
                    if(result.code === 100){
                        this.$message.success("创建成功");
                        this.contractNameAddDialogVisible = false;
                        this.contractForm.contractName = '';
                        this.getList();
                    }else{
                        this.$message.success("创建失败");
                    }
                })
            },

            /** 新增按钮操作 */
            handleAdd() {
                this.contractForm.contractName = '';
                this.contractNameAddDialogVisible = true;
            },

            /**锁定生成合同*/
            handlerLockContract(row){
                let that = this;
                this.$confirm('是否确认锁定生成合同？', "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(function() {
                    lockAndProduceContract(row.id,1).then(result=>{
                        if(result.code === 100){
                            that.msgSuccess(result.msg);
                            that.getList();
                        }else{
                            that.msgError(result.msg);
                        }
                    })
                }).then(() => {

                });
            },

            /**合同选择模版录入合同添加*/
            handlerAddContractShow(row){
                this.contractForm.contractId = row.id;
                getTemplateList().then(result =>{
                    if(result.code === 100){
                        this.contractTemplates = result.data.records;
                        this.contractAddDialogVisible = true;
                    }
                })
            },

            /**指定合同付费客户添加*/
            handlerContractCustomerDialogShow(row){
                this.contractCustomerDialogVisible = true;
                this.contractForm.contractId = row.id;
            },
            /**指定合同付费客户添加*/
            handlerContractCustomerAdd(){
                if(this.contractPaymentCustomer.id === undefined){
                    this.$message.error("请选择合同付费客户");
                    return;
                }
                let params = {
                    contractId: this.contractForm.contractId,
                    customerId: this.contractPaymentCustomer.id
                };
                addContractCustomer(params).then(result =>{
                    if(result.code === 100){
                        this.$message.success("添加成功");
                        this.contractCustomerDialogVisible = false;
                        this.getList();
                    }else{
                        this.$message.error("创建失败");
                    }
                })
            },

            /** 合同模版选择后获取模版字段  */
            handleTemplateSelected(){
                let template={};
                this.contractTemplates.forEach((val)=>{
                    if(val.id === this.contractForm.templateId){
                        template = val;
                    }
                });
                this.contractForm.templateRecordId = template.recordId;
                getTemplateFieldsById(template.recordId).then(response =>{
                    if(response.code === 100){
                        this.contractForm.formItems = response.data;
                    }
                })
            },

            /** 根据手机号码获取客户信息 */
            getCustomerByPhone(){
                let that = this;
                if(this.paymentCustomerPhone !== ''&& this.paymentCustomerPhone.length === 11){
                    getCustomerByPhone( this.paymentCustomerPhone, 2).then(response =>{
                        if(response.code === 100){
                            that.contractPaymentCustomer = response.data;
                            that.contractForm.customerId = that.contractPaymentCustomer.id;
                        }
                    })
                }
            },

            /** 客户类型选择*/
            customerChoose(formItem){
                this.currentContractSingerFormItem = formItem;
                this.customerType = formItem.type;
                this.customerIndex = formItem.index;
                this.customerLabel = formItem.label;
                if(this.customerType === 2){
                    this.customerChooseTile = '个人客户选择';
                }else{
                    this.customerChooseTile = '企业客户选择';
                }
                this.customerChooseDialogVisible = true;
            },
            /** 添加签署客户*/
            customerSearch(){
                let that = this;
                if(this.customerPhone !== ''&& this.customerPhone.length === 11){
                    getCustomerByPhone(this.customerPhone,this.customerType).then(response =>{
                        if(response.code === 100){
                            if(response.data != null){
                                that.customerInfo = response.data;
                                this.$message.success(response.msg);
                            }else{
                                this.$message.error(response.msg);
                            }

                        }
                    })
                }
            },

            /** 添加合同签署客户*/
            addContractSigners(){
                if(this.customerInfo !== undefined){
                    let signer = {
                        index: this.customerIndex, //合同模块索引
                        partName:this.customerLabel,//"签署方 债务人 债权人 共同债务人" 合同表单模块
                        customerId:this.customerInfo.id,//签署人ID/企业ID
                        customerType:this.customerType//
                    };
                    if(this.customerType === 2){
                        signer.customer = this.customerInfo;
                        this.currentContractSingerFormItem.tips = '已选择客户';
                    }else{
                        this.currentContractSingerFormItem.tips = '已选择企业';
                        signer.company = this.customerInfo;
                    }

                    if(this.contractSigners.length === 0){
                        this.contractSigners.push(signer);
                    }else{
                        let isContain = false;
                        this.contractSigners.forEach((item)=>{
                            if(item.index === signer.index){
                                if (item.customerType === 2) {
                                    item.partName = signer.partName;
                                    item.customerId = signer.customerId;
                                    item.customer = signer.customer;
                                }else{
                                    item.partName = signer.partName;
                                    item.customerId = signer.customerId;
                                    item.company = signer.company;
                                }
                                isContain = true;
                            }
                        });
                        if(!isContain){
                            this.contractSigners.push(signer);
                        }
                    }

                    this.currentContractSingerFormItem.items.forEach((item)=>{
                        if(this.currentContractSingerFormItem.index === signer.index){
                            if(signer.customerType === 2){
                                if(item.placeholderName === "姓名"){
                                    this.contractFormItems[item.placeholderKey] = signer.customer.name;
                                }else if(item.placeholderName === "身份证号"){
                                    this.contractFormItems[item.placeholderKey] = signer.customer.identity;
                                }else if(item.placeholderName === "电话"){
                                    this.contractFormItems[item.placeholderKey] = signer.customer.mobile;
                                }else if(item.placeholderName === "银行账号"){
                                    this.contractFormItems[item.placeholderKey] = signer.customer.bankCard;
                                }else if(item.placeholderName === "邮箱"){
                                    this.contractFormItems[item.placeholderKey] = signer.customer.email;
                                }else if(item.placeholderName === "地址"){
                                    this.contractFormItems[item.placeholderKey] = signer.customer.addr;
                                }else if(item.placeholderName === "紧急联系人姓名"){
                                    this.contractFormItems[item.placeholderKey] = signer.customer.emergencyName;
                                }else if(item.placeholderName ==="紧急联系人电话"){
                                    this.contractFormItems[item.placeholderKey] = signer.customer.emergencyPhone;
                                }
                            }else{
                                if(item.placeholderName === "姓名"){
                                    this.contractFormItems[item.placeholderKey] = signer.company.legalPerson;
                                }else if(item.placeholderName === "身份证号"){
                                    this.contractFormItems[item.placeholderKey] = signer.company.legalPersonIdentity;
                                }else if(item.placeholderName === "电话"){
                                    this.contractFormItems[item.placeholderKey] = signer.company.contactMobile;
                                }
                            }
                        }
                    });
                    this.customerChooseDialogVisible = false;
                    this.customerInfo = undefined;
                    this.customerPhone = '';
                }
            },

            /** 取消合同签署人搜索*/
            customerSearchAddCancel(){
                if(this.customerChooseDialogVisible){
                    this.customerChooseDialogVisible = false;
                    this.customerInfo = undefined;
                    this.customerPhone = '';
                }
            },

            /**合同添加提交按钮*/
            handleContractAdd(){
                let formData = {};
                this.contractForm.formItems.forEach((formItem)=>{
                    formItem.items.forEach((item)=>{
                        if(this.contractFormItems.hasOwnProperty(item.placeholderKey)){
                            item.value = this.contractFormItems[item.placeholderKey];
                        }
                        formData[item.placeholderKey] = item.value;
                    });
                });
                let contractInfo = {
                    contractId:  this.contractForm.contractId,
                    templeteId: this.contractForm.templateRecordId,
                    formItems: this.contractForm.formItems,
                    contractSigners: this.contractSigners, //合同签约客户
                    param:formData,
                };

                let that = this;
                this.$confirm('是否确认已关联签署客户？', "警告", {
                    confirmButtonText: "是，已关联客户",
                    cancelButtonText: "否，去关联客户",
                    type: "warning"
                }).then(function() {
                    saveContractDetail(contractInfo).then(result=>{
                        if(result.code === 100){
                            that.msgSuccess(result.msg);
                            that.contractAddDialogVisible = false;
                            that.contractForm.contractId = undefined;
                            that.contractForm.templateId = undefined;
                            that.contractForm.templateRecordId = undefined;
                            that.contractForm.formItems = [];
                            that.contractFormItems = [];
                            that.contractSigners = [];
                        }else{
                            that.msgError(result.msg);
                        }
                    })
                }).then(() => {

                });

            },

            handlerCancel(){
                this.contractForm.contractName = '';
                this.contractNameAddDialogVisible = false;
                if(this.contractAddDialogVisible){
                    this.contractForm.templateId = undefined;
                    this.contractForm.formItems = [];
                    this.contractAddDialogVisible = false;
                }

                this.contractCustomerDialogVisible = false;
            },

            /** 修改按钮操作 */
            handleUpdate(row) {
                this.resetQuery();
                const id = row.id || this.ids
                getContract(id).then(response => {
                    this.form = response.data;
                    this.open = true;
                    this.title = "修改合同主";
                });
            },
            /** 提交按钮 */
            submitForm() {
                this.$refs["form"].validate(valid => {
                    if (valid) {
                        if (this.form.id != null) {
                            updateContract(this.form).then(response => {
                                this.msgSuccess("修改成功");
                                this.open = false;
                                this.getList();
                            });
                        } else {
                            addContract(this.form).then(response => {
                                this.msgSuccess("新增成功");
                                this.open = false;
                                this.getList();
                            });
                        }
                    }
                });
            },
            /** 删除按钮操作 */
            handleDelete(row) {
                const name = row.contractName
                const ids = row.id || this.ids
                this.$confirm('是否确认删除合同名称为"' + name + '"的合同?', "警告", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(function() {
                    return delContract(ids);
                }).then(() => {
                    this.getList();
                    this.msgSuccess("删除成功");
                })
            },
            // 取消按钮
            cancel() {
                this.open = false;
                this.resetQuery();
            },
            //作废合同
            cancelContract(row) {
                const name = row.contractName
                const id = row.id
                this.$confirm('是否确认作废合同名称为"' + name + '"的合同?', "警告", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(function() {
                    return cancelContract({
                        contractId: id
                    });
                }).then(() => {
                    this.getList();
                    this.msgSuccess("作废成功");
                })
            },
            // 多选框选中数据
            handleSelectionChange(selection) {
                this.ids = selection.map(item => item.id);
                this.single = selection.length!==1;
                this.multiple = !selection.length
            },
            dateFormat: function (row, column) {
                const dateStr = row[column.property];
                if (dateStr != null) {
                    const dateMat = new Date(dateStr);
                    const year = dateMat.getFullYear();
                    const month = dateMat.getMonth() + 1;
                    const day = dateMat.getDate();
                    const hh = dateMat.getHours();
                    const mm = dateMat.getMinutes();
                    const ss = dateMat.getSeconds();
                    // const timeFormat = year + "-" + month + "-" + day + " " + hh + ":" + mm + ":" + ss;
                    // const timeFormat = year + "-" + month + "-" + day;
                    let timeFormat = year + '-' + (month < 10 ? '0' + month : month) + '-' + (day < 10 ? '0' + day : day)
                    return timeFormat
                }
            },

            contractDetailList: function (row) { // 查看合同流程里的合同信息列表
                // 组装路由名称, 并判断是否已添加, 如是: 则直接跳转
                // var routeName = `contract-flow-list`
                // var route = window.SITE_CONFIG['dynamicRoutes'].filter(item => item.name === routeName)[0]
                // if (route) {
                //   route.meta.title = `合同详情 - ${row.contractNo}`
                //   return this.$router.push({ name: route.name, params: { 'parentId': row.id, 'status': row.status } })
                // }
                // // 否则: 添加并全局变量保存, 再跳转
                // route = {
                //   path: routeName,
                //   component: () => import('@/views/modules/contract/contract-flow-list'),
                //   name: routeName,
                //   meta: {
                //     ...window.SITE_CONFIG['contentTabDefault'],
                //     menuId: this.$route.meta.menuId,
                //     title: `合同详情 - ${row.contractNo}`
                //   }
                // }
                // this.$router.addRoutes([
                //   {
                //     ...moduleRoutes,
                //     name: `main-dynamic__${route.name}`,
                //     children: [route]
                //   }
                // ])
                // window.SITE_CONFIG['dynamicRoutes'].push(route)
                // this.d2adminPagePoolPush(route)
                // this.$router.push({ name: 'contract-flow-list', params: { 'parentId': row.id, 'status': row.status } })
                this.parentId = row.id
                this.statusCode = parseInt(row.status)
                this.detailDialogVisible = true
                this.$nextTick(() => {
                    this.$refs.detailOrUpdate.dataForm.contractId = this.contractId
                    this.$refs.detailOrUpdate.init()
                })
            },

            addOrUpdateHandle: function (row) {
                this.addOrUpdateVisible = true
                this.contractId = row.id
                this.$nextTick(() => {
                    this.$refs.addOrUpdate.dataForm.contractId = this.contractId
                    this.$refs.addOrUpdate.init()
                })
            },
            downloadContract: function (id) {
                var link = document.createElement('a')
                link.style.display = 'none'
                link.href = process.env.VUE_APP_API + '/manager/contract/downloadContract?id=' + id
                document.body.appendChild(link)
                link.click()
                document.body.removeChild(link)
            },

            remoteMethod(query) {
                if (query !== '') {
                    this.loading = true;
                    this.getCompanyList(query);
                } else {
                    this.companyList = [];
                }
            },

            // 获企业客户所列表
            getCompanyList(queryName) {
                return this.$axios.get('/manager/company/page', {
                    params: {
                        order: 'ASC',
                        orderField: 'createTime',
                        current: 1,
                        size: 20,
                        listMode: true,
                        queryItems: 'name,LIKE,' + queryName
                    }
                }).then(res => {
                    this.loading = false;
                    this.companyList = res.records
                }).catch(() => {
                })
            },
          //退款
          openRefundDialog (contractId) {
            this.refundForm = {
              contractId: contractId,
              applyDesc: ''
            }
            this.refundDialogVisible = true
          },
          refund () {
            refund(this.refundForm).then(res => {
              if (res.code === 100) {
                this.getList();
                this.refundDialogVisible = false
                this.$message.success('申请成功')
              }
            })
          }
        }
    }
</script>
<style scoped>
    .el-divider--horizontal {
        display: block;
        height: 1px;
        width: 100%;
        margin: 15px 0;
    }
</style>
